package com.mgg.user.controller.profile;

import com.mgg.common.entity.ValidateCode;
import com.mgg.common.util.*;
import com.mgg.oss.properties.AliYunOSSProperties;
import com.mgg.oss.util.OSSUtils;
import com.mgg.user.entity.BankCardDO;
import com.mgg.user.enums.UserResultEnum;
import com.mgg.user.service.profile.ProfileService;
import com.mgg.user.service.user.UserService;
import com.mgg.user.vo.IdentifyCardVO;
import com.mgg.user.vo.ProfileVO;
import com.mgg.user.vo.UserInfoVO;
import com.mgg.user.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * @Author: lijun
 * @Date: 2018-09-01 10:22:00
 */
@RestController
@RequestMapping("/profile")
public class ProfileController {

    @Autowired
    private ProfileService profileService;

    @Autowired
    private UserService userService;

    @Autowired
    AliYunOSSProperties aliYunOSSProperties;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * userId查询用户信息
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/info")
    public Object getProfileInfo(@RequestHeader("user_id") String userId) throws Exception {
        if (StringUtils.isEmpty(userId)) {
            return ResultVOUtil.error(UserResultEnum.USER_QEURY_CONDITION_ERROR);
        }
        UserInfoVO userInfoVO = userService.getUserInfoByUserId(userId);
        return ResultVOUtil.success(userInfoVO);
    }

    /**
     * 修改用户信息
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping(value="/update")
    public Object updateProfile(@RequestHeader("user_id") String userId,
                                @RequestParam(required = false) String username,
                                @RequestParam(required = false) String headImg,
                                @RequestParam(required = false) String birthday,
                                @RequestParam(required = false) String sex,
                                @RequestParam(required = false) String region) throws Exception {
        if (!StringUtils.isEmpty(username)) {
            username = EmojiFilter.filterEmoji(username);
            username = EmojiFilter.removeFourChar(username);
        }
        profileService.updateProfile(userId, username, headImg, birthday, sex, region);
        UserInfoVO userInfoVO = userService.getUserInfoByUserId(userId);
        return ResultVOUtil.success(userInfoVO);
    }

    /**
     * 上传头像
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping(value="/headImg/upload")
    public Object uploadHeadImag(@RequestHeader("user_id") String userId,
                                 @RequestParam("image") MultipartFile image) throws Exception {
        String path = "user/headImg/" + DateUtils.getDays() + "/";
        String imageName = image.getOriginalFilename();
        String ossKey = path + UUIDUtils.get32UUID() + "." + imageName.substring(imageName.lastIndexOf(".") + 1);
        try{
            OSSUtils.upload(aliYunOSSProperties,ossKey,image.getInputStream());
        } catch (RuntimeException e) {
            return ResultVOUtil.error(UserResultEnum.IMAGE_UPLOAD_ERROR);
        }
        String headImg = aliYunOSSProperties.getDomain() + "/" + ossKey;
        profileService.updateProfile(userId,null,headImg,null,null,null);
        UserInfoVO userInfoVO = userService.getUserInfoByUserId(userId);
        return ResultVOUtil.success(userInfoVO);
    }

    /**
     * 上传身份证信息
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping(value="/identity/upload")
    public Object uploadIdentity(@RequestHeader("user_id") String userId,
                                 @RequestParam("frontImage") MultipartFile frontImageFile,
                                 @RequestParam("consImage") MultipartFile consImageFile,
                                 @RequestParam(value = "name", required = true) String realName,
                                 @RequestParam(value = "id", required = true) String identityNumber) throws Exception {
        try {
            String pathPrefix = "user/ID/";
            String frontImage = OSSUtils.upload(aliYunOSSProperties, pathPrefix, frontImageFile.getOriginalFilename(), frontImageFile.getInputStream());
            String consImage = OSSUtils.upload(aliYunOSSProperties, pathPrefix, consImageFile.getOriginalFilename(), consImageFile.getInputStream());
            profileService.saveUserIdentityCard(userId, realName, identityNumber, frontImage, consImage);
        } catch (RuntimeException e) {
            return ResultVOUtil.error(UserResultEnum.IMAGE_UPLOAD_ERROR);
        }
        UserInfoVO userInfoVO = userService.getUserInfoByUserId(userId);
        return ResultVOUtil.success(userInfoVO);
    }

    /**
     * 获取身份证信息
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping(value="/identity/info")
    public Object getUserIdentityCard(@RequestHeader("user_id") String userId) throws Exception {
        IdentifyCardVO identifyCardVO = profileService.getUserIdentityCard(userId);
        return ResultVOUtil.success(identifyCardVO);
    }

    /**
     * 微信账号绑定
     * @param smsCode
     * @return
     * @throws Exception
     */
    @PostMapping(value="/connect/weixin")
    public Object connectWeixin(@RequestHeader("user_id") String userId,
                                @RequestParam(value = "smsCode") String smsCode,
                                @RequestParam(value = "openid") String openid,
                                @RequestParam(value = "change") boolean change,
                                @RequestParam(value = "unionid", required = false) String unionid,
                                @RequestParam(value = "name", required = false) String name,
                                @RequestParam(value = "image", required = false) String image,
                                @RequestParam(value = "from", required = false) String from) throws Exception {
        UserInfoVO user = userService.getUserInfoByUserId(userId);
        // 判断验证码是否正确
        ValidateCode validateCode = (ValidateCode) redisTemplate.opsForValue().get("code:sms:" + user.getPhone());
        ValidateCodeUtils.checkCode(smsCode, validateCode);

        //判断openid是否已绑定
        String providerId = "weixin";
        UserVO wxUser = userService.getUserByOpenid(openid,providerId);
        if (wxUser != null) {
            if ("h5".equals(from)) {
                profileService.updateUserUnionid(userId,providerId,openid);
                return ResultVOUtil.success();
            } else {
                return ResultVOUtil.error(UserResultEnum.WEIXIN_CONNECTED);
            }
        }
        if (change) {
            profileService.deleteUserConnection(userId,providerId);
        } else {
            //判断账号是否已经绑定
            if (user.getProviderUser() != null && !StringUtils.isEmpty(user.getProviderUser().getOpenid())) {
                return ResultVOUtil.error(UserResultEnum.USER_WEIXIN_CONNECTED);
            }
        }
        name = EmojiFilter.filterEmoji(name);
        name = EmojiFilter.removeFourChar(name);
        profileService.insertUserConnection(userId,providerId,openid,unionid,name,image);
        profileService.updateUserUnionid(userId,providerId,openid);
        UserInfoVO userInfoVO = userService.getUserInfoByUserId(userId);
        return ResultVOUtil.success(userInfoVO);
    }

    /**
     * 解除微信绑定
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/connect/weixin/del")
    public Object delConnectWeixin(@RequestHeader("user_id") String userId) throws Exception {
        profileService.deleteUserConnection(userId,"weixin");
        UserInfoVO userInfoVO = userService.getUserInfoByUserId(userId);
        return ResultVOUtil.success(userInfoVO);
    }

    /**
     * 上传银行卡信息
     * @param userId
     * @return
     * @throws Exception
     */
    @PostMapping(value="/bankcard/upload")
    public Object uploadBankCard(@RequestHeader("user_id") String userId,
                                 @RequestParam("image") MultipartFile imageFile,
                                 @RequestBody BankCardDO bankCardDO) throws Exception {
        try {
            String pathPrefix = "user/ID/";
            String image = OSSUtils.upload(aliYunOSSProperties, pathPrefix, imageFile.getOriginalFilename(), imageFile.getInputStream());
            bankCardDO.setImage(image);
            bankCardDO.setUserId(userId);
            bankCardDO.setStatus("1");
            bankCardDO.setCreateTime(DateUtils.getTime());
            profileService.saveUserBankCard(bankCardDO);
        } catch (RuntimeException e) {
            return ResultVOUtil.error(UserResultEnum.IMAGE_UPLOAD_ERROR);
        }
        return ResultVOUtil.success();
    }

    /**
     * 银行卡列表
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/bankcard/list")
    public Object getUserBankCardList(@RequestHeader("user_id") String userId) throws Exception {
        List<Map<String,Object>> bankCardList = profileService.listUserBanlCardByUserId(userId);
        return ResultVOUtil.success(bankCardList);
    }
}
